<template>
  <div class="step-box">
    <div v-if="isShowFlag === 'one'">
      <el-row :gutter="20" class="page-box">
        <el-col :span="24" style="padding: 3% 10% 10px;">
          <p class="padding-line-height"><span class="font-weight">{{customerRiskInfo.customerName}}</span>先生/女士，您好！为了给您提供更优质的理财服务，请仔细阅读屏幕下方的风险承受能力评估问卷并如实填写，确认所填写内容为您本人真实表述。</p>
        </el-col>
        <el-col :span="24" class="padding-risk txt-right">
          <el-button type="primary" @click="sendBrowseQuestionClick">发送能力评估问卷</el-button>
        </el-col>
        <el-col :span="24" class="padding-risk">
          <el-col class="riskBox">
          <p class="padding-line-height txt-center"><span class="font-weight">客户评分</span></p>
          <p class="padding-line-height">
            以上问题的总分为65分，根据您所选择的问题答案，您对投资风险的整体承受程度及您的风险偏好总得分为：<span class="font-weight">{{score}}分</span>。
            根据本评估表的测试结果您的风险承受能力为：
            <span v-if="score >= '53' && score <= '65'">
              <span class="font-weight">53-65分 □积极型 您属于可以承受高风险类型的投资者。</span>
              您适合投资于能够为您提供高升值能力而投资价值波动大的投资工具。最坏的情况下，您可能失去全部投资本金并需对您投资所导致的任何亏蚀承担责任。
            </span>
            <span v-else-if="score >= '40' && score <= '52'">
              <span class="font-weight">40-52分 □成长型 您属于可以承担中等至高风险类型的投资者。</span>
              您适合投资于能够为您提供升值能力，而投资价值有波动的投资工具。
            </span>
            <span v-else-if="score >= '28' && score <= '39'">
              <span class="font-weight">28-39分 □平衡型 您属于可以承担中等风险类型的投资者。</span>
              您适合投资于能够为您提供温和升值能力，而投资价值有温和波动的投资工具。
            </span>
            <span v-else-if="score >= '16' && score <= '27'">
              <span class="font-weight">16-27分 □稳健型 您属于可以承担低至中等风险类型的投资者。</span>
              您适合投资于能够权衡保本而亦有若干升值能力的投资工具。
            </span>
            <span v-else-if="score <= '15'">
              <span class="font-weight">15分或以下 □保守型 您属于可以承担低风险而作风谨慎类型的投资者。</span>
              您适合投资于以保本为主的投资工具，但您因此会牺牲资本升值的机会。
            </span>
          </p>
          </el-col>
        </el-col>
        <el-col :span="24" class="padding-risk">
          <p class="padding-line-height" style="color: #ff3939;padding: 0px 10px">再次提醒您，根据上述问卷评估，您属于<span class="font-weight" style="color: black;">{{investType}}投资者</span>，理财有风险，投资需谨慎。请您在屏幕下方签字确认：</p>
        </el-col>
        <el-col :span="24" style="padding: 0 10%;">
          <el-col><h4>客户签名</h4></el-col>
          <el-col class="signNameBox mt10">
            <el-col style="width: 100%;height: 100%;" class="txt-center"><h2 v-if="cardAssignFlag">客户签名区</h2><img style="width: 100%;" v-if="!cardAssignFlag" :src='cusSignBase64' alt=""></el-col>
          </el-col>
        </el-col>
        <el-col class="view-bottom">
          <el-row :gutter="20">
            <el-col :span="12" class="txt-right">
              <el-button type="primary" @click="sendAssignClick"><span v-text="assignHtml"></span></el-button>
            </el-col>
            <el-col :span="12" class="txt-left">
              <el-button type="primary" @click="nextStep2">确认</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div v-else-if="isShowFlag === 'two'" class="mt5 custInfo-box">
      <el-row class="view-header">风险测评业务确认单</el-row>
      <el-row class="view-middle">
        <BizCertForm :option="bizCertOption" :data="bizCertData"></BizCertForm>
      </el-row>
      <el-row class="view-bottom">
        <el-row :gutter="20">
          <el-col :span="12" class="txt-right">
            <el-button type="primary" @click="bizCertFail">拒绝</el-button>
          </el-col>
          <el-col :span="12" class="txt-left">
            <el-button type="primary" @click="bizCertSuccess">通过</el-button>
          </el-col>
        </el-row>
      </el-row>
    </div>
    <div v-else-if="isShowFlag === 'three'" class="mt5 custInfo-box">
      <el-row class="view-box">
        <el-row class="view-header">认证结果</el-row>
        <el-row>
          <el-row class="photo-box">
            <div class="success-photo center">
              <img src='assets/theme/img/viceoBiz/success.png' alt="">
            </div>
            <el-row class="photo-title" style="margin: 10px 0px"><h2>风评结束</h2></el-row>
          </el-row>
        </el-row>
        <el-row class="view-bottom">
        </el-row>
      </el-row>
    </div>
    <div v-else-if="isShowFlag === 'four'" class="mt5 custInfo-box">
      <el-row class="view-box">
        <el-row class="view-header">认证结果</el-row>
        <el-row>
          <el-row class="photo-box">
            <div class="success-photo center">
              <img src='assets/theme/img/viceoBiz/cardFail.png' alt="">
            </div>
            <el-row class="photo-title" style="margin: 10px 0px"><h2>认证失败</h2></el-row>
            <el-row class="padding-line-height txt-center">失败原因：{{reasonDescribe}}</el-row>
          </el-row>
        </el-row>
        <el-row class="view-bottom">

        </el-row>
      </el-row>
    </div>
    <el-dialog title="凭证预览" :visible.sync="dialogVisible" top="20px" width="95%">
      <el-scrollbar style="height: 500px;">
        <img style="width: 100%" :src="bizCertUrl" alt="">
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="openVideoUploadFileFun">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="拒绝申请" :visible.sync="dialogFormVisibleFail" append-to-body width="70%">
      <el-row>
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入拒绝原因……"
          v-model="failReason" resize="none">
        </el-input>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 10px;" @click="dialogFormVisibleFail = false">取 消</el-button>
        <el-button type="primary" @click="bizCertFailClick">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import $ from 'jquery'
  import Axios from 'axios'
  import html2canvas from 'html2canvas'
  import BizCertForm from '@/views/videoBiz/phoneBank/common/bizCertForm'
  import {
    uploadFile,
    submitBizCert,
    imgTransBase64,
    saveTransPipeline
  } from '@/api/videoBiz/videoBiz'

  export default {
    name: 'riskAssessmentVideo',
    components: {
      BizCertForm
    },
    data() {
      return {
        isShowFlag: 'one',
        cardAssignFlag: true,
        assignHtml: '签名',
        customerRiskInfo: {},
        questionPhoto: '',
        score: '',
        investType: '',
        dialogFormVisibleFail: false,
        failReason: '',
        dialogVisible: false,
        bizCertUrl: '',
        frontName: '',
        reverseName: '',
        cusSceneName: '',
        bizCertName: '',
        frontCardPhoto: '',
        frontBase64: 'assets/theme/img/viceoBiz/frontPhoto.png',
        reverseBase64: 'assets/theme/img/viceoBiz/reversePhoto.png',
        cusSceneBase64: 'assets/theme/img/viceoBiz/perpr.png',
        cusSignBase64: '',
        frontCardBase64: '',
        bizCertData: {},
        bizCertOption: {},
        bizCertSeqNo: '',
        cardActiveFlag: false,
        reasonDescribe: ''
      }
    },
    created() {

    },
    mounted() {
      /********************************** 小程序交互信令 ****************************************/
      let self = this
      self.bizCertOption = window.videoOptions.openHouseVideoOption.phoneBankFRAOption
      // 工作台结束会话
      window.eventEmitter.$on('EventVideoChatDone', () => {
        Constants.ModelChat = {}
        let biztype = sessionStorage.getItem('businessType')
        if ('风险测评' == biztype) {
          self.activeName = 'third'
          window.ctpMenuOption.home.redirectName = 'phoneBankRiskAssessment'
          self.resetGlobalVarible()
          self.isShowFlag = 'one'
          self.nextStep(0)
        }
      })
      // 视频进线
      window.eventEmitter.$on('EventPhoneBankFRARing', (data) => {
        console.log(JSON.stringify(data))
        self.resetGlobalVarible()
        self.isShowFlag = 'one'
        self.nextStep(0)
        self.customerRiskInfo = data.customerInfo
        self.saveTransPipelineFun()
        sessionStorage.setItem('businessType', data.customerInfo.businessType)
      })
      // 发送调查问卷结果(填完调查问卷之后)
      window.eventEmitter.$on('EventRiskQuestionResult', (data) => {
        self.questionPhoto = data.questionPhoto
        self.score = data.score
        self.investType = data.investType
      })
      // 收到签名照片
      window.eventEmitter.$on('EventRiskGetBizSign', (data) => {
        // 客户签名照片
        if (data.cusSignCard) {
          imgTransBase64(data.cusSignCard).then(response => {
            self.cardAssignFlag = false
            self.cusSignBase64 = response.data
            self.assignHtml = '重新签名'
          }).catch(error => {
            console.log(error)
          })
        }
      })
      // 收到面签业务申请单
      window.eventEmitter.$on('EventRiskGetBizSignForm', (data) => {
        // 身份证正面照
        if (data.frontIDCard) {
          self.frontName = data.frontIDCard
          imgTransBase64(data.frontIDCard).then(response => {
            self.frontBase64 = response.data
            self.$set(self.bizCertData, 'frontPhoto', self.frontBase64)
          }).catch(error => {
            console.log(error)
          })
        }
        // 身份证反面照
        if (data.reverseIDCard) {
          self.reverseName = data.reverseIDCard
          imgTransBase64(data.reverseIDCard).then(response => {
            self.reverseBase64 = response.data
            self.$set(self.bizCertData, 'backPhoto', self.reverseBase64)
          }).catch(error => {
            console.log(error)
          })
        }
        // 客户头像
        if (data.cusSceneCard) {
          self.cusSceneName = data.cusSceneCard
          imgTransBase64(data.cusSceneCard).then(response => {
            self.cusSceneBase64 = response.data
            self.$set(self.bizCertData, 'customerPhoto', self.cusSceneBase64)
          }).catch(error => {
            console.log(error)
          })
        }
        // 卡正面照
        if (data.frontCardPhoto) {
          self.frontCardPhoto = data.frontCardPhoto
          imgTransBase64(data.frontCardPhoto).then(response => {
            self.frontCardBase64 = response.data
            self.$set(self.bizCertData, 'frontCardPhoto', self.frontCardBase64)
          }).catch(error => {
            console.log(error)
          })
        }
        // 电子凭证信息
        self.bizCertData = {
          /************************************ 交易信息 *************************************/
          // 客户姓名
          'name': data.customerInfoList.name,
          // 身份证号码
          'idCard': data.customerInfoList.idCard,
          // 电话号码
          'tel': data.customerInfoList.tel,
          // 联系地址
          'address': data.customerInfoList.address,
          // 职业
          'profession': data.customerInfoList.profession,
          // 职业中类
          'professionType': data.customerInfoList.professionType,
          // 正面照
          'frontPhoto': self.frontBase64,
          // 反面照
          'backPhoto': self.reverseBase64,
          // 联网核查结果
          'internetResult': data.customerInfoList.internetResult,
          // 人像比对结果
          'onlineResult': data.customerInfoList.onlineResult,
          // 客户人像
          'customerPhoto': self.cusSceneBase64,
          // 卡正面照
          'frontCardPhoto': self.frontCardBase64,
          /************************************ 交易信息 *************************************/
          // 户名
          'accountName': data.tradInfoList.accountName,
          // 卡号
          'tradIdCard': data.tradInfoList.idCard,
          // 业务类型
          'businessType': data.tradInfoList.businessType,
          // 投资类型
          'investType': self.investType,
          // 客户签名
          'customerSignature': self.cusSignBase64,
          // 交易日期
          'transactionDate': data.tradInfoList.transactionDate,
          // 客服人员编号
          'managerNum': Constants.Agent.agentId,
          // 客服人员姓名
          'manager': Constants.Agent.agentName
        }
        // 更新客户信息交易流水
        self.updateTransPipelineFun(true, false)
      })
    },
    methods: {
      // 步骤条步进
      nextStep(index) {
        this.$emit('nextStep', index)
      },
      // 发送能力评估问卷申请
      sendBrowseQuestionClick() {
        globalUserData.sendBrowseQuestionnaire()
      },
      // 发送签名请求
      sendAssignClick() {
        console.log('签名')
        globalUserData.sendEventRiskResBizSign()
      },
      // 跳转到业务申请单界面
      nextStep2() {
        if (window.Settings.nextStepFlag) {
          this.cardAssignFlag = false
        }
        if (this.cardAssignFlag) {
          globalUiKit.notify('提示', '请先执行签名操作！', 'error')
          return
        }
        this.nextStep(1)
        this.isShowFlag = 'two'
        globalUserData.sendEventRiskFormStep()
      },
      // 拒绝申请单
      bizCertFail() {
        this.dialogFormVisibleFail = true
      },
      bizCertFailClick() {
        if (!this.failReason) {
          globalUiKit.notify('提示', '拒绝原因不能为空！', 'error')
          return
        }
        this.dialogFormVisibleFail = false
        globalUserData.sendEventRiskFail(this.failReason)
        this.updateTransPipelineFun(true, false)
        this.isShowFlag = 'four'
        this.nextStep(2)
        this.failReason = ''
      },
      // 接口失败全局变量控制
      globalBizCertFail(message) {
        this.cardActiveFlag = false
        this.dialogVisible = false
        this.failReason = message
        this.nextStep(2)
        this.isShowFlag = 'four'
        globalUserData.sendEventRiskFail(this.failReason)
        this.updateTransPipelineFun()
      },
      // 通过申请单
      bizCertSuccess() {
        let self = this
        html2canvas(document.querySelector("#bizVideoHouseCertCanvas"), {
          allowTaint: false
        }).then(function (canvas) {
          console.log('biz cert canvas is: ' + canvas.toDataURL())
          self.dialogVisible = true
          self.bizCertUrl = canvas.toDataURL()
        })
      },
      // 凭证推送到影像平台
      openVideoUploadFileFun() {
        let bizCertBlob = Utils.dataURLtoBlob(this.bizCertUrl)
        let formData = new FormData()
        formData['enctype'] = 'multipart/form-data'
        formData.append('file', bizCertBlob)
        uploadFile(formData).then(response => {
          console.log('response biz cert link is: ' + response.data)
          this.bizCertName = response.data
          if (window.Settings.imgLinkUploadFlag) {
            this.submitTransImgUploadFun()
          } else {
            this.submitBizCertFun()
          }
        }).catch(error => {
          console.log(error)
          if (window.Settings.imgLinkUploadFlag) {
            this.submitTransImgUploadFun()
          } else {
            this.submitBizCertFun()
          }
        })
      },
      // 上传影像平台
      submitBizCertFun() {
        // 3 文件链接
        let params = {
          "fileInfos": [{
            "fileType": "卡片",
            "fileTypeCode": "2603001",
            "fileUrl": this.frontCardPhoto
          }, {
            "fileType": "身份证正面",
            "fileTypeCode": "2603002",
            "fileUrl": this.frontName
          }, {
            "fileType": "身份证反面",
            "fileTypeCode": "2603003",
            "fileUrl": this.reverseName
          }, {
            "fileType": "客户现场照",
            "fileTypeCode": "2603004",
            "fileUrl": this.cusSceneName
          }, {
            "fileType": "业务确认单",
            "fileTypeCode": "2603005",
            "fileUrl": this.bizCertName
          },
//            {
//            "fileType": "问卷调查",
//            "fileTypeCode": "2603005",
//            "fileUrl": this.questionPhoto
//          }
          ],
          "filePartName": "ZNKFSCFXPGP",
          "modeCode": "ZNKFSCFXPG",
          "modelName": "理财首次风险评估",
          "sessionId": Constants.ModelChat.sid
        }
        console.log('request submit biz cert data: ' + JSON.stringify(params))
        submitBizCert(params).then(response => {
          let data = response.data
          console.log('response submit biz form data: ' + JSON.stringify(data))
          this.bizCertSeqNo = data.data
          if (200 == data.code) {
            this.cardActiveFlag = true
            this.dialogVisible = false
            this.nextStep(2)
            this.isShowFlag = 'three'
            globalUserData.sendEventRiskSuccess()
            this.updateTransPipelineFun()
          } else {
            if (!data.message) {
              data.message = 'submit biz form failed！'
            }
            this.reasonDescribe = '提交电子凭证失败！'
            this.globalBizCertFail(data.message)
            globalUiKit.notify('提示', '提交电子凭证失败！', 'error')
          }
        }).catch(error => {
          console.log(error)
          error = 'submit biz form failed！'
          this.reasonDescribe = '提交电子凭证失败！'
          this.globalBizCertFail(error)
          globalUiKit.notify('提示', '电子凭证接口请求失败！', 'error')
        })
      },
      // 保存影像平台交易流水
      submitTransImgUploadFun() {
        this.dialogVisible = false
        this.nextStep(2)
        this.isShowFlag = 'three'
        globalUserData.sendEventRiskSuccess()
        this.updateTransPipelineFun(false, true)
      },
      // 记录交易流水
      saveTransPipelineFun: function () {
        let params = {
          'transactionDate': '',
          'transactionTime': '',
          'transactionNo': '',
          'channelType': Constants.ModelChat.chatType,
          'sessionId': Constants.ModelChat.sid,
          'transactionAmount': '',
          'isSatisfaction': '',
          'docidNo': Constants.ModelChat.sid,
          'businessType': '理财首次风险评估',
          'idCardType': '身份证',
          'agentNo': Constants.Agent.agentId,
          'agentName': Constants.Agent.agentName,
          'errorMsg': this.failReason,
          'filePartName': 'ZNKFSCFXPGP',
          'modelCode': 'ZNKFSCFXPG',
          'startDate': '',
          'endDate': '',
          'principalName': '',
          'principalIdType': '',
          'principalIdNum': '',
          'unitedSocialCreditNo': ''
        }
        console.log('request save trans pipeline data: ' + JSON.stringify(params))
        saveTransPipeline(params).then(response => {
          let data = response.data
          console.log('response save trans pipeline data: ' + JSON.stringify(data))
          if (200 == data.code) {
            console.log('记录交易流水成功')
            globalUiKit.notify('提示', '视频交易流水记录成功！', 'success')
          } else {
            console.log('记录交易流水失败')
            window.globalUiKit.alert('视频交易流水记录失败', '失败原因：' + data.message + '；入参：' + JSON.stringify(params))
          }
        }).catch(error => {
          console.log(error)
          window.globalUiKit.alert('视频交易流水记录失败', '失败原因：' + error + '；入参：' + JSON.stringify(params))
        })
      },
      // 更新交易流水
      updateTransPipelineFun: function (customerFlag, imgLinkUploadFlag) {
        let params = {
          'sessionId': Constants.ModelChat.sid,
          'errorMsg': this.failReason,
          'channelType': Constants.ModelChat.chatType,
          'sessionId': Constants.ModelChat.sid,
          'docidNo': Constants.ModelChat.sid,
          'businessType': '理财首次风险评估',
          'idCardType': '身份证',
          'agentNo': Constants.Agent.agentId,
          'agentName': Constants.Agent.agentName,
          'errorMsg': this.failReason,
          'filePartName': 'ZNKFSCFXPGP',
          'modelCode': 'ZNKFSCFXPG',
          'transactionStatus': '成功'
        }
        // 确认凭证保存客户信息
        if (customerFlag) {
          params.cardNo = this.bizCertData.tradIdCard
          params.accountName = this.bizCertData.accountName
          params.idCardNo = this.bizCertData.idCard
          params.customerName = this.bizCertData.name
        }
        // 保存影像平台图片
        if (imgLinkUploadFlag) {
          params.frontImge = this.frontName
          params.backImge = this.reverseName
          params.card = this.frontCardPhoto
          params.csImge = this.cusSceneName
          params.businessImge = this.bizCertName
          params.uploadFlag = 'img'
        }
        console.log('request update trans pipeline data: ' + JSON.stringify(params))
        saveTransPipeline(params).then(response => {
          let data = response.data
          console.log('response update trans pipeline data: ' + JSON.stringify(data))
          if (200 == data.code) {
            console.log('更新交易流水成功')
            globalUiKit.notify('提示', '视频交易流水记录成功！', 'success')
          } else {
            console.log('更新交易流水失败')
            window.globalUiKit.alert('视频交易流水记录失败', '失败原因：' + data.message + '；入参：' + JSON.stringify(params))
          }
        }).catch(error => {
          console.log(error)
          window.globalUiKit.alert('视频交易流水记录失败', '失败原因：' + error + '；入参：' + JSON.stringify(params))
        })
      },
      // 全局变量重置
      resetGlobalVarible: function () {
        this.frontName = ''
        this.reverseName = ''
        this.cusSceneName = ''
        this.bizCertName = ''
        this.questionPhoto = ''
        this.score = ''
        this.investType = ''
        this.frontCardPhoto = ''
        this.frontBase64 = 'assets/theme/img/viceoBiz/frontPhoto.png'
        this.reverseBase64 = 'assets/theme/img/viceoBiz/reversePhoto.png'
        this.cusSceneBase64 = 'assets/theme/img/viceoBiz/perpr.png'
        this.cusSignBase64 = ''
        this.frontCardBase64 = ''
        this.bizCertData = {}
        this.failReason = ''
        this.bizCertUrl = ''
        this.dialogFormVisibleFail = false
        this.dialogVisible = false
        this.customerRiskInfo = {}
        this.assignHtml = '签名'
        this.cardAssignFlag = true
        this.bizCertSeqNo = ''
        this.cardActiveFlag = false
        this.reasonDescribe = ''
        sessionStorage.removeItem('businessType')
      }
    }
  }
</script>
<style scoped>
  .step-box {
    width: 100%;
    margin: 0 auto;
  }

  .font-weight{
    font-weight: bold;
  }

  /************************************* 页面一 *********************************************/
  .mt5 {
    margin-top: 5px;
  }

  .mt15 {
    margin: 15px 0px;
  }

  .papers-photo {
    height: 186px;
    width: 274px;
  }

  .papers-photo img {
    height: 100%;
    width: 100%;
  }

  .card-media-photo img {
    height: 100%;
    width: 100%;
  }

  .center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .peror-photo {
    height: 200px;
    width: 186px;
    overflow: hidden;
  }

  .peror-photo img {
    height: 100%;
    width: 100%;
  }

  .per-result {
    margin: 10px 0;
  }

  /************************************* 页面三 *********************************************/
  .mb10 {
    margin-bottom: 10px;
  }

  .custInfo-box {
    padding: 0px 6%;
  }

  /************************************* 页面四 *********************************************/
  .page-box {
    height: 100%;
    width: 100%;
  }

  .left-box, .right-box {
    height: 750px;
  }

  .paddinglr0 {
    padding-right: 0px !important;
    padding-left: 0px !important;
  }

  .mt10 {
    margin-top: 10px;
  }

  .view-header {
    height: 40px;
    text-align: center;
    line-height: 40px;
    background-color: #f5f7fa;
  }

  .view-middle {
    /*height: 650px;*/
  }

  .view-bottom {
    text-align: center;
    height: 55px;
    line-height: 55px;
  }

  .riskBox{
    width: 100%;
    border: 1px dashed #ddd;
    padding: 10px 20px;
  }

  .padding-risk{
    padding: 10px 10% !important;
  }

  .signNameBox {
    width: 100%;
    height: 225px;
    line-height: 225px;
    border: 1px dashed #ddd;
  }

  /***********************************交易结束********************************************/
  .photo-title {
    padding-top: 20px;
    text-align: center;
  }

  .exceed-photo {
    width: 62px;
    height: 62px;
    margin: 0 auto;
  }

  .photo-box {
    padding-top: 80px;
  }

  .padding-line-height {
    line-height: 26px;
  }

</style>
